from DrissionPage import WebPage, ChromiumOptions, SessionOptions
import platform
import getpass
import random
import time


system = platform.system()
if system.startswith('Windows'):
    EXEC_DIR_PATH = f'C:/Users/{getpass.getuser()}/AppData/Local/Google/Chrome/Application/chrome.exe'
    USER_DIR_PATH = f'C:/Users/{getpass.getuser()}/AppData/Local/Google/Chrome/User_Data'
elif system.startswith('Apple'):
    EXEC_DIR_PATH = f'/Users/{getpass.getuser()}/Library/Application Support/Google/Chrome/Application/chrome'
    USER_DIR_PATH = f'/Users/{getpass.getuser()}/Library/Application Support/Google/Chrome/User_Data'
elif system.startswith('Linux'):
    EXEC_DIR_PATH = f'/home/{getpass.getuser()}/AppData/Local/Google/Chrome/Application/chrome'
    USER_DIR_PATH = f'/home/{getpass.getuser()}/AppData/Local/Google/Chrome/User_Data'


def get_browser_1() -> WebPage:
    co = ChromiumOptions()
    co.set_headless(False)
    co.set_argument('--start-maximized')
    co.remove_argument('--enable-automation')
    co.set_paths(browser_path=EXEC_DIR_PATH, user_data_path=USER_DIR_PATH)
    return WebPage(driver_or_options=co)


def get_browser_2() -> WebPage:
    import subprocess
    import time
    '''
    --remote-debugging-port=9999 是指定运行端口，只要没被占用就行
    --user-data-dir 指定运行浏览器的运行数据，新建一个干净目录，不影响系统原来的 数据
    --incognito 隐私模式打开
    --start-maximized 窗口最大化
    --new-window 直接打开网址
    '''
    # 启动命令
    command = f'{EXEC_DIR_PATH} --remote-debugging-port=9999 --remote-allow-origins=* --start-maximized'
    subprocess.Popen(command, shell=True)
    time.sleep(1)
    co = ChromiumOptions()
    co.set_headless(False)
    co.set_argument('--start-maximized')
    co.remove_argument('--enable-automation')
    co.debugger_address = 'http://localhost:9999'
    co.set_paths(browser_path=EXEC_DIR_PATH, user_data_path=USER_DIR_PATH, local_port=9999)
    return WebPage(driver_or_options=co)


def close_browser(browser: WebPage):
    print('退出程序')
    browser.quit()


# 随机打开内容item
def random_click(page: WebPage, info_list: [], css_selector: str=None, limit: int=3):
    count = 0
    origin_page = page.get_tab(page.latest_tab)
    while count < limit and count < len(info_list):
        count = count + 1
        idx = random.randint(0, len(info_list) - 1)
        href = info_list[idx].attr('href')
        page.run_js(f'window.open("{href}", "_blank");')
        # 暂停3秒
        time.sleep(3)
        # 新标签页
        page.wait.new_tab()
        current_page = page.get_tab(page.latest_tab)
        # 执行回调函数
        if css_selector is not None:
            info_items = current_page.eles('css:' + css_selector)
            random_click(page, info_items, None, limit)
        # 关闭标签页
        page.close_tabs(tabs_or_ids=current_page)
        page.set.tab_to_front(tab_or_id=origin_page)
